package com.lp.common.util;

import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public final class HttpClientUtil{
    protected static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * get
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static  String get(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);

        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        logger.info("request:"+sb);
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        OkHttpClient okHttpClient =  SpringUtils.getBean(OkHttpClient.class);;
        try(  Response response =   okHttpClient.newCall(request).execute())
          {
            int status = response.code();
            if (response.isSuccessful()) {
                 responseBody= response.body().string();
                logger.info("response:"+responseBody);
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e));
        }
        return responseBody;
    }



    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        logger.info("request:"+url+":param:"+builder.toString());
        OkHttpClient okHttpClient =  SpringUtils.getBean(OkHttpClient.class);;
        try( Response response = okHttpClient.newCall(request).execute()) {
            int status = response.code();
            if (response.isSuccessful()) {
                responseBody= response.body().string();
                logger.info("response:"+responseBody);
            }
        } catch (Exception e) {
            logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        }
        return responseBody;
    }

    /**
     * get
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String getForHeader(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        logger.info("request:"+sb);
        Request request = new Request.Builder()
                .addHeader("key", "value")
                .url(sb.toString())
                .build();
        OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
        try( Response response = okHttpClient.newCall(request).execute();)
        {
            int status = response.code();
            if (response.isSuccessful()) {
                responseBody= response.body().string();
                logger.info("response:"+responseBody);
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        }
        return responseBody;
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        logger.info("request:"+jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
        try( Response response = okHttpClient.newCall(request).execute();){
            int status = response.code();
            if (response.isSuccessful()) {
                responseBody= response.body().string();
                logger.info("response:"+responseBody);
            }
        } catch (Exception e) {
            logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        }
        return responseBody;
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        logger.info("request:"+xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
        try( Response response = okHttpClient.newCall(request).execute();){
            int status = response.code();
            if (response.isSuccessful()) {
                responseBody= response.body().string();
                logger.info("response:"+responseBody);
            }
        } catch (Exception e) {
            logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        }
        return responseBody;
    }
public static  void main(String[] args)throws  Exception {
Map p=new HashMap();
p.put("MfcISAPICommand","EmsTransnv");
p.put("cdata","<OP>0</OP><DATE>2018.11.08 12:15:30</DATE><PID>GG12345</PID><CID>01</CID><NUM>11201174611</NUM><DES>US</DES><WEIGHT>2.345</WEIGHT><MD5>b683b7cfee79be33329104272f461e25</MD5>");
//HttpClientUtil.post("http://47.101.184.188/cgi-bin/GInfo.dll",p);

  String str= HttpClientUtil.get("http://wl.huachu100.cn/index.php?s=/addon/PbAddon/mobile/ajax/mpid/1&province=%E5%85%A8%E5%9B%BD+%E5%85%A8%E5%9B%BD&type=%E7%B1%BB%E5%9E%8B&keyword=&page=1",null);


}


}